<template>
  <mt-popup
    v-model="visible"
    position="bottom"
    class="fdx-share-popup fdx-share-box"
    ref="sharePopover">
    <ul class="share-list">
      <li v-if="shareTyes.wx">
        <i
          class="icon-weixin-friend"
          @click="share('weixin')"></i>
        <span>微信</span>
      </li>
      <li v-if="shareTyes.friends">
        <i
          class="icon-weixin-friends"
          @click="share('pengyouquan')"></i>
        <span>朋友圈</span>
      </li>
      <li v-if="shareTyes.qq">
        <i
          class="icon-qq"
          @click="share('qq')"></i>
        <span>QQ</span>
      </li>
      <li v-show="type==='picture'">
        <i
          class="fdx-icon-cloud-download"
          @click="save"></i>
        <span>保存图片</span>
      </li>
    </ul>
  </mt-popup>
</template>
<script type="text/ecmascript-6">
import { isIOS } from 'assets/js/app'
export default {
  props: {
    type: {
      type: String,
      default: 'content' // 分享页面为content,分享图片为picture
    },
    href: String,
    title: String,
    content: String,
    thumb: {
      type: String,
      default: '_www/img/logo-login.png'
    },
    picture: String,
    shareTyes: {
      type: Object,
      default: () => {
        return {
          wx: true,
          friends: true,
          qq: true
        }
      }
    }
  },
  data() {
    return {
      visible: false,
      shares: {},
      isContent: true,
      ids: {
        weixin: {
          id: 'weixin',
          ex: 'WXSceneSession',
          title: '发送给微信好友'
        },
        pengyouquan: {
          id: 'weixin',
          ex: 'WXSceneTimeline',
          title: '分享到微信朋友圈'
        },
        qq: {
          id: 'qq',
          title: '分享到QQ'
        }
      },
      sharesFlag: false
    }
  },
  mounted: function() {
    var self = this
    plus &&
      plus.share &&
      plus.share.getServices(
        function(s) {
          if (s && s.length > 0) {
            for (var i = 0; i < s.length; i++) {
              var t = s[i]
              self.shares[t.id] = t
            }
          }
          self.sharesFlag = true
        },
        function() {
          console.log('获取分享服务列表失败')
        }
      )
  },
  watch: {
    type: function(val) {
      this.isContent = val === 'content'
    }
  },
  methods: {
    show() {
      this.visible = true
    },
    close() {
      this.visible = false
    },
    getFilePath(url) {
      var newUrl = url.lastIndexOf('?') > 0 ? url.split('?')[0] : url
      return (
        '_downloads/' +
        newUrl.substring(newUrl.lastIndexOf('/') + 1, newUrl.length)
      )
    },
    checkLocalIsExist(url, exitCallback, nonExitCallback) {
      var path = this.getFilePath(url)
      plus.io.resolveLocalFileSystemURL(
        path,
        function(entry) {
          exitCallback(path)
        },
        function(e) {
          nonExitCallback(path)
        }
      )
    },
    getImgFromLocal(path) {
      return plus.io.convertLocalFileSystemURL(path)
    },
    getImgFromNet: function(url, path, success, error) {
      // 创建下载任务
      var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
        if (status === 200) {
          success(d.filename)
        } else {
          error(path)
        }
      })
      // 启动下载任务
      dtask.start()
    },
    delFile(relativePath) {
      plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
        entry.remove(
          function(entry) {
            console.log('文件删除成功')
          },
          function(e) {
            console.log('文件删除失败')
          }
        )
      })
    },
    shareMessage(share, ex) {
      var self = this
      var url = this.picture
      if (this.type === 'content') {
        this.sendMessage(share, ex)
      } else {
        const ios = isIOS()
        if (!ios) {
          /* andrioid
           * 1.从本地获取, 如果本地存在, 从本地获取图片
           * 2.如果本地不存在则下载缓存到本地
           */
          this.checkLocalIsExist(
            url,
            function(path) {
              // 本地存在,则直接获取本地图片
              var localPath = self.getImgFromLocal(path)
              self.sendMessage(share, ex, localPath)
            },
            function(path) {
              // 本地文件不存在,下载图片
              self.getImgFromNet(
                url,
                path,
                function(path) {
                  // 下载成功
                  var localPath = self.getImgFromLocal(path)
                  self.sendMessage(share, ex, localPath)
                },
                function(path) {
                  alert(2)
                  // 下载失败,需删除本地临时文件,否则下次进来时会检查到图片已存在
                  // dtask.abort();// 文档描述:取消下载,删除临时文件;(但经测试临时文件没有删除,故使用delFile()方法删除);
                  if (path != null) self.delFile(path)
                }
              )
            }
          )
        } else {
          // ios直接使用网络地址
          this.sendMessage(share, ex, url)
        }
      }
    },
    sendMessage(share, ex, url) {
      var msg = {
        extra: {
          scene: ex
        }
      }
      if (this.type === 'content') {
        msg = Object.assign({}, msg, {
          href: this.href,
          title: this.title,
          content: this.content,
          thumbs: [this.thumb]
        })
        window.trackOperation('分享', '内容', this.title, this.href)
      } else {
        msg = Object.assign({}, msg, { pictures: [url] })
        // alert(JSON.stringify(msg))
        window.trackOperation('分享', '图片', url)
      }
      share.send(
        msg,
        () => {
          Toast('分享成功')
          this.$emit('success')
        },
        function(e) {
          var code = e.message
            .substring(e.message.indexOf('[') + 1, e.message.indexOf(']'))
            .split(':')[1]
          switch (code) {
            case '-98':
              Toast('请先安装微信客户端')
              break
            case '2':
            case '-6':
              Toast('请先安装QQ客户端')
              break
            default:
              Toast('分享失败')
          }
          console.log(
            '分享到"' +
              share.description +
              '"失败: ' +
              e.code +
              ' - ' +
              e.message
          )
        }
      )
      this.close()
      setTimeout(() => {
        Indicator.close()
      }, 2000)
    },
    share(type) {
      var self = this
      if (!this.sharesFlag) {
        return Toast('分享服务错误！')
      }
      Indicator.open()
      var shareType = this.ids[type]
      var s_id = shareType.id
      var share = this.shares[s_id]
      if (share.authenticated) {
        self.shareMessage(share, shareType.ex)
      } else {
        share.authorize(
          function() {
            self.shareMessage(share, shareType.ex)
          },
          function(e) {
            Toast('认证授权失败')
            console.log('认证授权失败：' + e.code + ' - ' + e.message)
            self.close()
          }
        )
      }
    },
    saveImgToGallary(url) {
      plus.gallery.save(
        url,
        function() {
          Toast('保存成功')
        },
        function(e) {
          console.log('保存失败: ' + JSON.stringify(e))
        }
      )
    },
    save() {
      var self = this
      var url = this.picture
      if (_.startsWith(url, 'http://') || _.startsWith(url, 'https://')) {
        const ios = isIOS()
        if (!ios) {
          /* andrioid 下载图片,然后保存本地临时文件 */
          this.getImgFromNet(
            url,
            this.getFilePath(url),
            function(path) {
              // 下载成功
              var localPath = self.getImgFromLocal(path)
              self.saveImgToGallary(localPath)
            },
            function(path) {
              // 下载失败,需删除本地临时文件
              if (path != null) self.delFile(path)
            }
          )
        } else {
          /* ios 保存网络图片 */
          this.saveImgToGallary(url)
        }
      } else {
        Toast('保存失败')
      }
      this.close()
    }
  }
}
</script>
<style  lang="scss">
.fdx-share-box {
  // right: 0;
  // bottom: 0;
  // left: 0;
  // transform: translate3d(0, 0, 0);
  width: 100%;
}

.fdx-share-box .share-list {
  height: 140px;
  background-color: #f8f8f8;
  display: flex;
  flex-flow: row;
  padding: 0 7px;
}

.fdx-share-box .share-list li {
  flex: 1;
  text-align: center;
  padding-top: 23px;
  animation: share-item 0.4s cubic-bezier(0.4, 0, 0, 1.5);
}

.fdx-share-box .share-list li:nth-child(1) {
  animation-delay: 0.04s;
}

.fdx-share-box .share-list li:nth-child(2) {
  animation-delay: 0.08s;
}

.fdx-share-box .share-list li:nth-child(3) {
  animation-delay: 0.12s;
}
.fdx-share-box .share-list li:nth-child(4) {
  animation-delay: 0.16s;
}

.fdx-share-box .share-list li i {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 70px;
  height: 70px;
  background-color: #fff;
  border-radius: 50%;
  text-align: center;
  margin: 0 auto;
  color: #515151;
  font-size: 38px !important;
}

.fdx-share-box .share-list li i:after {
  content: "";
  display: inline-block;
  background-repeat: no-repeat;
  background-size: contain;
}

.fdx-share-box .share-list li i.icon-weixin-friend:after {
  width: 35px;
  height: 33px;
  background-image: url(./weixin-friend.png);
}

.fdx-share-box .share-list li i.icon-weixin-friends:after {
  width: 31px;
  height: 31px;
  background-image: url(./weixin-friends.png);
}

.fdx-share-box .share-list li i.icon-qq:after {
  width: 32px;
  height: 35px;
  background-image: url(./qq.png);
}

.fdx-share-box .share-list li span {
  display: block;
  color: #222;
  font-size: 14px;
  margin-top: 5px;
}

.fdx-share-box button {
  display: block;
  width: 100%;
  height: 48px;
  background-color: #fff;
  color: #222;
  font-size: 16px;
  border-top: 1px solid #ddd;
}

.fdx-share-box button:before {
  display: none;
}

@keyframes share-item {
  0% {
    opacity: 0;
    transform: translate3d(0, 100%, 0);
  }
  100% {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}
</style>
